package info.fastpace.android.utils;

import info.fastpace.utils.Config;

import java.io.Serializable;

import android.content.Context;
import android.content.Intent;
import android.os.Looper;

/**
 * Saves the state of the intent in the memory (static and instance based) in addition to persistency.
 * 
 *
 * @param <T>
 */
public class MemoryIntent<T extends Serializable> extends Intent {
	
	private static final String KEY = "KEY";
	private static Serializable MEMORY_INSTANCE;
	private T memoryInstance;

	public MemoryIntent(Context packageContext, T t, Class<?> clazz) {
		super(packageContext, clazz);
        if (Thread.currentThread() != Looper.getMainLooper().getThread()) {
        	Config.getLog().w("Creating Intent out of the UI thread");
        }
		MEMORY_INSTANCE = t;
		memoryInstance = t;
		putExtra(KEY, t);
	}

	public MemoryIntent(android.content.Intent intent) {
		super(intent);
        if (Thread.currentThread() != Looper.getMainLooper().getThread()) {
        	Config.getLog().w("Creating Intent out of the UI thread");
        }
		getInstance(); // Do not erase. This is a must in order initiate the instance from the UI thread
	}

	/**
	 *  
	 */
	@SuppressWarnings("unchecked")
	public T getInstance() {
		if (memoryInstance != null) {
			return memoryInstance;
		}
		if (MEMORY_INSTANCE != null) {
			memoryInstance = (T) MEMORY_INSTANCE;
			// Nullify on purpose to make activities save the instance - in order not to reuse a previous (other) returned instance.
			MEMORY_INSTANCE = null;
		}else {
			memoryInstance = (T) getSerializableExtra(KEY);
		}
		return memoryInstance;
	}
	
	protected void setInstance(T t) {
		memoryInstance = t;
		putExtra(KEY, t);
	}
}
